from umqtt.simple import MQTTClient
from machine import Pin
import network
import time

ssid='HelloWorld'
passwd='456258000'
client_id = "slim_id"
mserver = '192.168.101.2'
port=1883

topic_ctl = b'led_ctl'#设备订阅的主题,客户端推送消息的主题
topic_sta = b'led_sta'#客户端订阅的主题,设备推送消息的主题
client = None
wlan = None

led1=Pin(2, Pin.OUT, value=1)
led2=Pin(5, Pin.OUT, value=1)
    
def sub_callback(topic, msg):
    """
    收到订阅消息回调
    """
    global client
    print((topic_ctl, msg))
    if msg == b'led1 ON' or msg == b'led1 on':
        pub_msg = 'LED1: ON-state'
        led1.value(0)
    elif msg == b'led1 OFF' or msg == b'led1 off':
        pub_msg = 'LED1: OFF-state'
        led1.value(1)
    elif msg == b'led2 ON' or msg == b'led2 on':
        pub_msg = 'LED2: ON-state'
        led2.value(0)
    elif msg == b'led2 OFF' or msg == b'led2 off':
        pub_msg = 'LED2: OFF-state'
        led2.value(1)
    else:
        pub_msg = 'other msg'
    client.publish(topic_sta, pub_msg, retain=True)

def connectWiFi():
    """
    连接到WiFi网络
    """
    global wlan
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    wlan.disconnect()
    wlan.connect(ssid, passwd)
    while(wlan.ifconfig()[0]=='0.0.0.0'):
        time.sleep(1)

try:
    connectWiFi()
    client = MQTTClient(client_id, mserver, 0, 'admin', 'public')
    client.set_callback(sub_callback)
    client.connect()
    client.subscribe(topic_ctl)
    client.publish(topic_sta, 'ESP32 Device online', retain=True)
    print("Connected to %s, subscribed to %s topic" % (mserver, topic_ctl))
    while True:
        client.wait_msg()
finally:
    if client is not None:
        print('off line')
        client.disconnect()
    wlan.disconnect()
    wlan.active(False)

